import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import router, {resetRouter} from '@/router'
import store from "@/store";

const getDefaultState = () => {
	return {
		token: getToken(),
		username: '',
		avatar: ''
	}
}

const state = getDefaultState()

const mutations = {
	RESET_STATE: (state) => {
		Object.assign(state, getDefaultState())
	},
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_NAME: (state, username) => {
		state.username = username
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	}
}

const actions = {
	// user login
	login({commit, dispatch}, userInfo) {
		const {username, password} = userInfo
		return new Promise((resolve, reject) => {
			login({username: username.trim(), password: password}).then(response => {
				const {data} = response
				commit('SET_TOKEN', data.token)
				setToken(data.token)
				dispatch('getInfo')
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// get user info
	async getInfo({commit}) {
		const {data, code} = await getInfo()
		if (code === 200) {
			const {username, avatar} = data
			commit('SET_NAME', username)
			commit('SET_AVATAR', avatar)
			await store.dispatch('permission/generateRoutes')
		}
	},

	// user logout
	logout({commit, state}) {
		// return new Promise((resolve, reject) => {
		// 	logout(state.token).then(() => {
		// 		removeToken() // must remove  token  first
		// 		resetRouter()
		// 		commit('RESET_STATE')
		// 		resolve()
		// 	}).catch(error => {
		// 		reject(error)
		// 	})
		// })
		removeToken() // must remove  token  first
		resetRouter()
		commit('RESET_STATE')
		return true
	},

	// remove token
	resetToken({commit}) {
    return new Promise(resolve => {
			removeToken() // must remove  token  first
			commit('RESET_STATE')
      router.push('/login')
      resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}

